package com.atguigu.gmall.weball.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.cart.CartFeignClient;
import com.atguigu.gmall.product.entity.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-16 13:03
 **/
@Controller
public class CartController {
    @Autowired
    CartFeignClient cartFeignClient;

    /* 这种方式【只放不删】就可能无限膨胀导致【OOM】 有put 就得 有remove
     * public static Map<Thread,HttpServletRequest> map = new ConcurrentHashMap<>();
     */
    /* 上面的写法等同于ThreadLocal
     * public static ThreadLocal<HttpServletRequest> threadLocal = new ThreadLocal<>();
     *
     */

    /**
     * 添加商品到购物车
     *
     * @param skuId
     * @param num
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/addCart.html")
    public String addToCart(
            @RequestParam("skuId") Long skuId,
            @RequestParam("skuNum") Integer num,
            Model model,
            HttpServletRequest request) {
        Result<SkuInfo> result = cartFeignClient.addToCart(skuId, num);
        if (result.isOk()) {
            SkuInfo skuInfo = new SkuInfo();
            model.addAttribute("skuInfo", result.getData());
            model.addAttribute("skuNum", num);
            // 到添加成功页
            return "cart/addCart";
        } else {
            model.addAttribute("msg", result.getMessage());
            return "cart/addCartErr";
        }
    }

    /**
     * 购物车列表
     *
     * @return
     */
    @GetMapping("/cart.html")
    public String toCartListPage() {
        return "cart/index";
    }

    /**
     * http://cart.gmall.com/cart/deleteChecked
     */
    @GetMapping("/cart/deleteChecked")
    public String deleteChecked() {
        cartFeignClient.delChecked();
        // 去首页 ， 如果只写了/cart.html，会指向服务器地址
        return "redirect:http://cart.gmall.com/cart.html";
    }
}
